package com.yinp.proapp.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import androidx.fragment.app.Fragment;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.yinp.proapp.R;
import com.yinp.proapp.base.activity.AppBaseActivity;
import com.yinp.proapp.base.fragment.BaseFragment;
import com.yinp.proapp.bean.UploadFile;
import com.yinp.proapp.constant.HttpUrl;
import com.yinp.proapp.constant.jiekou.OnLubanFinishListener;
import com.yinp.proapp.manger.BaseManager;
import com.yinp.proapp.view.PermissionDialog;
import com.yinp.proapp.web.erp_retrofit.ErpObserver;
import com.yinp.proapp.web.erp_retrofit.PictureData;
import com.yinp.proapp.web.retrofit.BuildRetrofit;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import okhttp3.MultipartBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class SelectPhotos {
    public static void checkPermission(Activity activity, BGASortableNinePhotoLayout itemPhotos) {
        checkPermission(activity, itemPhotos, 1);
    }

    /**
     * 应用于拍照
     */
    public static void checkPermission(Activity activity, BGASortableNinePhotoLayout itemPhotos, int requestCode) {
        String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        XXPermissions.with(activity)
                .permission(permission) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            openAlbum(activity, itemPhotos, requestCode);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            PermissionDialog permissionDialog = new PermissionDialog(activity, activity.getString(R.string.per_tips, activity.getString(R.string.storage)), permissions);
                            permissionDialog.show();
                        }
                    }
                });
    }

    public static void checkPermission(Fragment fragment, BGASortableNinePhotoLayout itemPhotos, int requestCode) {
        String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        XXPermissions.with(fragment)
                .permission(permission) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            openAlbum(fragment, itemPhotos, requestCode);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            PermissionDialog permissionDialog = new PermissionDialog(fragment.getActivity(), fragment.getString
                                    (R.string.per_tips, fragment.getString(R.string.storage)), permissions);
                            permissionDialog.show();
                        }
                    }
                });
    }

    /**
     * 打开相册
     */
    private static void openAlbum(Activity activity, BGASortableNinePhotoLayout itemPhotos, int requestCode) {
        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
        File takePhotoDir = new File(activity.getExternalFilesDir(null), "ErpTakePhoto");

        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(activity)
                .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                .maxChooseCount(itemPhotos.getMaxItemCount() - itemPhotos.getItemCount()) // 图片选择张数的最大值
                .selectedPhotos(null) // 当前已选中的图片路径集合
                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                .build();
        activity.startActivityForResult(photoPickerIntent, requestCode);
    }

    private static void openAlbum(Fragment fragment, BGASortableNinePhotoLayout itemPhotos, int requestCode) {
        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
        File takePhotoDir = new File(fragment.getActivity().getExternalFilesDir(null), "ErpTakePhoto");

        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(fragment.getActivity())
                .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                .maxChooseCount(itemPhotos.getMaxItemCount() - itemPhotos.getItemCount()) // 图片选择张数的最大值
                .selectedPhotos(null) // 当前已选中的图片路径集合
                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                .build();
        fragment.startActivityForResult(photoPickerIntent, requestCode);
    }

    /**
     * 压缩
     */
    public static void compressImage(Context context, List<String> list, OnLubanFinishListener listener) {
        List<File> listFile = new ArrayList<>();
        listFile.clear();
        for (int i = 0; i < list.size(); i++) {
            Luban.with(context)
                    .load(list.get(i))
                    .filter(path1 -> !(TextUtils.isEmpty(path1) || path1.toLowerCase().endsWith(".gif")))
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        }

                        @Override
                        public void onSuccess(File file) {
                            listFile.add(file);
                            if (list.size() == listFile.size()) {
                                listener.finish(listFile);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过程出现问题时调用
                        }
                    }).launch();
        }
    }

    /**
     * 上传照片(多张)
     */
    public static void uploadFile(AppBaseActivity activity, BaseManager presenter, List<File> files, AA aa) {
        uploadFile(activity, presenter, files, 0, aa);
    }

    public static void uploadFile(BaseFragment fragment, List<File> files, AA aa) {
        uploadFile(fragment, files, 0, aa);
    }

    public static void uploadFile(AppBaseActivity activity, BaseManager presenter, List<File> files, int position, AA aa) {
        List<MultipartBody.Part> listPart = FileUtils.imagesToMultipartBodyParts("file", files);
        presenter.addDisposable(BuildRetrofit.getInstance(HttpUrl.UPLOAD_FILE).getApiRetrofit().uploadFileMore(listPart), new ErpObserver<List<UploadFile>>() {
            @Override
            public void onSuccess(PictureData<List<UploadFile>> o) {
                aa.getValue(o.getResult(), position);
                activity.hideLoading();
            }

            @Override
            public void onCodeFail(String msg,int code) {
                activity.hideLoading();
                activity.showToast(msg);
            }
        });
    }

    public static void uploadFile(BaseFragment fragment, List<File> files, int position, AA aa) {
        List<MultipartBody.Part> listPart = FileUtils.imagesToMultipartBodyParts("file", files);
    }

    public abstract static class AA {
        public void getValue(List<UploadFile> list, int position) {
        }
    }
}
